package com.base.api.hwn.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.base.api.hwn.LogService;
import com.base.dao.hwn.InsuranceTransactionRecordMapper;
import com.base.utils.ResultUtil;
import com.base.utils.WebSocketServer;
import com.base.vo.hwn.InsuranceTransactionRecord;
import com.base.vo.hwn.MipsSettlementInfo;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LogServiceImpl implements LogService {


    @Autowired
    private InsuranceTransactionRecordMapper iTranRecordH;

    @Override
    public String testWebSocket(String sessionId) {
        for (int i = 0; i < 100; i++) {
            try {
                WebSocketServer.sendInfo("这是第------->" + i + "<-------条消息", sessionId);
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "success";
    }

    @Override
    public String queryUnilateral(String jsonStr, String startDate, String endDate, String yblx) {
        String jsonString = assemblyPara(startDate, endDate, yblx);
        String result = doPost(jsonString);
        JSONObject jsonObject;
        try {
            jsonObject = JSON.parseObject(result).getJSONObject("args");
        } catch (Exception e) {
            Map<String, Object> map2 = new HashMap<>();
            map2.put("count", 0);
            map2.put("data", new ArrayList<>());
            map2.put("code", 100);
            map2.put("msg", "后台调用医保接口失败," + e.getLocalizedMessage());
            return JSON.toJSONString(map2);
        }

        //System.out.println(jsonObject);
        if (jsonStr == null) {

        }
        List<InsuranceTransactionRecord> recordList = new ArrayList<>();
        JSONArray resultSet = jsonObject.getJSONArray("resultSet");
        for (int i = 0; i < resultSet.size(); i++) {
            JSONObject jo = resultSet.getJSONObject(i);
            String jyscMsg = jo.getString("jyscMsg");
            if (jyscMsg == null) {
                jyscMsg = jo.getString("JyscXml");
            }
            String[] rows = jyscMsg.split("\n");
            if (rows.length > 1) {
                for (String column : rows) {
                    String[] columns = column.split("\t");
                    InsuranceTransactionRecord itr = new InsuranceTransactionRecord();
                    itr.setPro1(columns[0]);
                    itr.setPro2(columns[1]);
                    itr.setPro3(columns[2]);
                    itr.setPro4(columns[3]);
                    itr.setPro5(columns[4]);
                    itr.setPro6(columns[5]);
                    itr.setPro7(columns[6]);
                    itr.setPro8(columns[7]);
                    itr.setPro9(columns[8]);
                    itr.setPro10(columns[9]);
                    itr.setPro11(columns[10]);
                    itr.setPro12(columns[11]);
                    itr.setPro13(columns[12]);
                    itr.setPro14(columns[13]);
                    itr.setPro15(columns[14]);
                    itr.setPro16(columns[15]);
                    itr.setPro17(columns[16]);
                    itr.setPro18(columns[17]);
                    itr.setPro19(columns[18]);
                    itr.setPro20(columns[19]);
                    itr.setPro21(columns[20]);
                    itr.setPro22(columns[21]);
                    itr.setPro23(columns[22]);
                    itr.setPro24(columns[23]);
                    itr.setPro25(columns[24]);
                    itr.setPro26(columns[25]);
                    if (columns.length > 26) {
                        itr.setPro27(columns[26]);
                        itr.setPro28(columns[27]);
                        itr.setPro29(columns[28]);
                    }
                    recordList.add(itr);
                }
            }
        }
        int total = iTranRecordH.selectcountBymap(startDate, endDate);
        List<MipsSettlementInfo> mipsSettlementInfos = iTranRecordH.selectListByMap(startDate, endDate);
        List<Map<String, Object>> list = new ArrayList<>();
        List<InsuranceTransactionRecord> newList = getdffList(recordList, mipsSettlementInfos);
        Map<String, Object> map = new HashMap<>();
        map.put("count", newList.size());
        map.put("data", newList);
        map.put("code", 0);
        map.put("msg", "");
        return JSON.toJSONString(map);
    }

    @Override
    public String doPost(String JsonStr) {
        String result = "后台请求异常！";
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String data = "{\"action\":\"SY_JINBAO_CALL\",\"args\":{\"commandSet\":[{\"areaCode\":\"12103\",\"jybh\":\"1100\",\"jysrParam\":\"1100^12103^10882^^20191204235830^0000^20191201|20191204|^\"}]}}";
        JsonStr = JsonStr.replaceAll("\"", "\\\"");
        StringEntity requestEntity = new StringEntity(JsonStr, "utf-8");
        requestEntity.setContentEncoding("UTF-8");
        // {"action":"SY_JINBAO_CALL","args":{"commandSet":[{"areaCode":"12103","jybh":"1100","jysrParam":"1100^12103^10882^^20191204235830^0000^20191201|20191204|^"}]}}
        String url = "http://192.168.127.99:8088";
        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);
        // 设置ContentType(注:如果只是传普通参数的话,ContentType不一定非要用application/json)
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        httpPost.setEntity(requestEntity);

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                result = EntityUtils.toString(responseEntity);
                System.out.println("响应内容为:" + result);
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }

    }


    public String assemblyPara(String startDate, String endDate, String yblx) {
        String jybh = "";
        String jysr = "";
        String qybm = "";
        String action = "";
        String commandSet = "";
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> map1 = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();
        if ("42030002".equals(yblx)) {
            action = "SYPMEDICARE_CALL";
            jybh = "46";
            jysr += "<?xml version='1.0' encoding='GBK' standalone='yes' ?>";
            jysr += "<input>";
            jysr += "<aae030>" + startDate + "</aae030>";
            jysr += "<aae031>" + endDate + "</aae031>";
            jysr += "<ykb065></ykb065>";
            jysr += "<outputfile>D:\\\\sjm\\\\catog.txt</outputfile>";
            jysr += "</input>";
            commandSet = "\"Jybh\":\"" + jybh + "\",\"JysrXml\":\"" + jysr + "\"";
        } else {
            action = "SY_JINBAO_CALL";
            jybh = "1100";
            if ("42030001".equals(yblx)) {
                qybm = "12103";
            }
            if ("42030011".equals(yblx)) {
                qybm = "42038101004";
            }
            jysr = "1100^" + qybm + "^10882^^" + System.currentTimeMillis() + "^0000^" + startDate.replaceAll("-", "") + "|" + endDate.replaceAll("-", "") + "|^";
            commandSet = "\"areaCode\":\"" + qybm + "\",\"jybh\":\"1100\",\"jysrParam\":\"" + jysr + "\"";
        }
        String result = "{\"action\":\"" + action + "\",\"args\":{\"params\":{\"filePath\": \"\"},\"commandSet\":[{" + commandSet + "}]}}";
        return result;
    }


    public List<InsuranceTransactionRecord> getdffList(List<InsuranceTransactionRecord> list1, List<MipsSettlementInfo> list2) {
        List<InsuranceTransactionRecord> list3;
        if (list1.size() == 0 && list1 == null) {
            return null;
        } else {
            list3 = new ArrayList<>();
            Map<String, Integer> map = new HashMap<>();
            for (InsuranceTransactionRecord itr : list1) {
                if (itr.pro29 != null && !"".equals(itr.pro29)) {
                    map.put(itr.pro6, 1);
                } else {
                    map.put(itr.pro3, 1);
                }

            }
            for (MipsSettlementInfo ms : list2) {
                if (map.get(ms.settlementNo) != null) {
                    map.put(ms.settlementNo, 100);
                }
            }
            for (InsuranceTransactionRecord itr : list1) {
                if (itr.pro29 != null && !"".equals(itr.pro29)) {
                    if (map.get(itr.pro6) == 1) {
                        list3.add(itr);
                    }
                } else {
                    if (map.get(itr.pro3) == 1) {
                        list3.add(itr);
                    }
                }

            }
        }
        return list3;
    }


}
